import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

import static java.lang.Math.random;

public class ForkJoinUtil {
    static void executeForkJoinTask() {
        long[] array = new long[2000_000];
        long expectedSum = 0;
        for(int i = 0; i < array.length; i++) {
            array[i] = (long) (random() * 5);
            expectedSum += array[i];
        }
        System.out.println("Expected sum is " + expectedSum);
        ForkJoinTask<Long> task = new SumTask(array, 0 ,array.length);
        long startTime = System.currentTimeMillis();
        Long result = ForkJoinPool.commonPool().invoke(task);
        long endTime = System.currentTimeMillis();
        System.out.println("sum is: " + result + " cost time is: " + (endTime - startTime) + "ms");
    }
}

class SumTask extends RecursiveTask<Long> {
    static final int THRESHOLD = 5000;
    long[] array;
    int start;
    int end;

    SumTask(long[] array, int start, int end) {
        this.array = array;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        if(end - start <= THRESHOLD) {
            long sum = 0;
            for(int i = start; i < end; i++) {
                sum += this.array[i];
                try {
                    Thread.sleep(1);
                } catch(InterruptedException _) {

                }

            }
            return sum;
        }
        int middle = (end + start) / 2;
        System.out.println(String.format("split %d~%d ==> %d~%d, %d~%d", start, end, start, middle, middle, end));
        SumTask task1 = new SumTask(array, start, middle);
        SumTask task2 = new SumTask(array, middle, end);
        invokeAll(task1, task2);
        Long subResult1 = task1.join();
        Long subResult2 = task2.join();
        Long result = subResult1 + subResult2;
        System.out.println("result = " + subResult1 + " + " + subResult2 + "===>" + result);
        return result;
    }
}
